package com.bizmda.bizsip.app.listener;

import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.bizmda.bizsip.app.service.AppService;
import com.bizmda.bizsip.common.BizConstant;
import com.bizmda.bizsip.common.BizMessage;
import com.bizmda.log.trace.MDCTraceUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageBuilder;
import org.springframework.amqp.core.MessageDeliveryMode;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.nio.charset.StandardCharsets;

/**
 * RabbitMQ接收服务
 * @author shizhengye
 */
@Slf4j
@Service
public class AppServiceQueueListener {
    @Autowired
    private AppService appService;
    @Autowired
    private RabbitTemplate rabbitTemplate;

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = BizConstant.APP_SERVICE_QUEUE, durable = "true", autoDelete = "false"),
            exchange = @Exchange(value = BizConstant.APP_SERVICE_EXCHANGE),
            key = BizConstant.APP_SERVICE_ROUTING_KEY))
    public void onMessage(Message inMessage) {
        try {
            this.process(inMessage);
        } catch (Exception e) {
            log.error("App服务侦听器处理出错!",e);
        }
    }

    private void process(Message inMessage) {
        JSONObject jsonObject;
        String str = new String(inMessage.getBody(), StandardCharsets.UTF_8);
        jsonObject = JSONUtil.parseObj(str);
        BizMessage<JSONObject> bizMessage = this.appService.process(jsonObject.getStr(BizConstant.APP_SERVICE_SERVICE_ID),jsonObject.getStr(BizConstant.APP_SERVICE_TRACE_ID),jsonObject.getJSONObject("data"));
        JSONObject jsonObject1 = JSONUtil.parseObj(bizMessage);
        String correlationId = inMessage.getMessageProperties().getCorrelationId();
        String replyTo = inMessage.getMessageProperties().getReplyTo();
        if (CharSequenceUtil.isEmpty(replyTo)) {
            return;
        }
        Message message = MessageBuilder.withBody(JSONUtil.toJsonStr(jsonObject1).getBytes(StandardCharsets.UTF_8))
                .setDeliveryMode(MessageDeliveryMode.PERSISTENT)
                .setContentType(MessageProperties.CONTENT_TYPE_JSON)
                .setCorrelationId(correlationId).build();
        message.getMessageProperties().setHeader(BizConstant.RABBITMQ_MESSAGE_HEADER_TRACE_ID, MDCTraceUtils.getTraceId());

        this.rabbitTemplate.send("", replyTo, message);
    }
}
